import axios from 'axios'
import Router from '@/router/index'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'

import {
  getToken,
  setToken,
  removeToken,
  getUserInfo,
  setUserInfo,
  removeUserInfo,
} from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})
// service.defaults.withCredentials = true;

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    /* console.log(config.data,'传过去的数据',config) */
    config.data = JSON.stringify(config.data)

    config.headers['Content-Type'] = 'application/json'

    if (getToken()) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {

    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code * 1 !== 20000 || !res.flag) {
      console.log(res, '状态码响应信息')
    }
    // 对响应数据做点什么
    if (response.message === '认证过期' || response.data.message === '请先登录' || response.data.code === 20011 || response.data
      .code === 20007) {
      // 移除token
      store.dispatch('user/logout');
      Router.replace({
        path: '/login'
      })
      Message.closeAll();
      Message.error(err.data.message || '登录过期,请先登录')
    } else if (response.data.message === '执行出错') {
      Message.closeAll()
      Message({
        message: response.data.message || '数据获取异常，请稍后重试。',
        showClose: true,
        type: 'error'
      })
    }
    return response
  },
  error => {
    console.log(error, error.response, '请求报错信息')
    let err = error.response;
    if (err) {
      if (err.data.code === 20007 || err.data.code === 20011 || err.data.code === 20015 || err.data.message ===
        '认证失败' || err.data.message ===
        '请先登录' || err.data.message ===
        '认证过期') {
        store.dispatch('user/logout');
        Router.replace({
          path: '/login'
        })
        Message.closeAll();
        if (err.data.code === 20015) {
          Message.error('你的账号被冻结，请联系管理员以解决此问题。')
        } else {
          Message.error(err.data.message || '登录过期,请先登录')
        }

      } else {
        Message.closeAll();
        Message.error(err.data.message || '数据获取异常，请稍后重试。')
      }
    } else {
      let errorStr = JSON.stringify(error);
      var str;
      if (errorStr.indexOf('timeout') !== -1) {
        str = '数据获取异常，请稍后重试。'
      } else if (errorStr.indexOf('Network') !== -1) {
        str = '数据获取异常，请稍后重试。'
      }
      Message.closeAll();
      Message({
        message: str,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(err)
    }


  }
)

export default service
